package threading;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-07-29
 * Time: 11:42
 */
//自己实现一个阻塞队列


public class ThreadDemoTest1 {
    public static void main(String[] args) {
        MyBlockingQueue1 myBlockingQueue1 = new MyBlockingQueue1();

        Thread t1 = new Thread(()->{
            while(true) {
                try {
                    int value = myBlockingQueue1.take();
                    System.out.println("消耗元素："+value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });

        Thread t2 = new Thread(()->{
            int value = 0;
            while(true) {
                try {
                    System.out.println("生产元素："+value);
                    myBlockingQueue1.put(value);
                    Thread.sleep(1000);
                    value++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });

        t1.start();
        t2.start();
    }
}

class MyBlockingQueue1 {
    private int[] items = new int[1000];
    volatile private int head = 0;
    volatile private int tail = 0;
    volatile private int size = 0;

    synchronized public void put(int value) throws InterruptedException {
        while(size == items.length) {
//            return;
            this.wait();
        }
        items[tail] = value;
        tail++;

        if(tail == items.length) {
            tail = 0;
        }
        size++;
        this.notify();
    }

    synchronized public Integer take() throws InterruptedException {
        while(size == 0) {
//            return null;
            this.wait();
        }
        int value = items[head];
        head++;

        if(head == items.length) {
            head = 0;
        }
        size--;
        this.notify();
        return  value;
    }
}
